package com.magic.shop.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.magic.shop.entity.TestOrder;
import com.magic.shop.util.AliPayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
@Slf4j
public class AliPayController {
    // 支付宝沙箱网关地址

    //    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";

    private static final String CHARSET = "UTF-8";

    private static final String SIGN_TYPE = "RSA2";





    @GetMapping("/pay")
    public void pay( @RequestParam  String trackingNumber, HttpServletResponse httpResponse) throws Exception{
        //Orders orders = ordersService.getOrdersByTrackingNumber(trackingNumber);
        TestOrder order=new TestOrder();
        order.setOrderNo(UUID.randomUUID().toString());
        order.setTotalAmount(new BigDecimal("0.1"));
        log.info("开始支付=====订单信息==={}==", com.alibaba.fastjson.JSONObject.toJSONString(order));
        //创建订单
        if (order == null){
            return ;
        }
        //1.创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient= new DefaultAlipayClient(GATEWAY_URL, AliPayUtils.appId,
                AliPayUtils.appPrivateKey,FORMAT,CHARSET,AliPayUtils.alipayPublicKey,SIGN_TYPE);


        //2.创建Request并设置Request参数
        AlipayTradePagePayRequest request=new AlipayTradePagePayRequest();
        request.setNotifyUrl(AliPayUtils.notifyUrl);
        JSONObject bizContent=new JSONObject();
        bizContent.set("out_trade_no",order.getOrderNo());
        bizContent.set("total_amount",order.getTotalAmount());
        bizContent.set("subject","aaa支付测试");//标题
        bizContent.set("product_code",AliPayUtils.PRODUCT_CODE1);
        request.setBizContent(bizContent.toString());
      //  request.setReturnUrl("http://localhost:8080/front/Order");//支付完成后回调url

        String form="";
        try {
            form=alipayClient.pageExecute(request).getBody();
        }catch (AlipayApiException e){
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" +CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    @PostMapping("/notify")
    public  void payNotify(HttpServletRequest request) {
        try {
            if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
                System.out.println("======支付宝异步回调======");
                Map<String, String> params = new HashMap<String, String>();
                Map requestParams = request.getParameterMap();
                for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                    String name = (String) iter.next();
                    String[] values = (String[]) requestParams.get(name);
                    String valueStr = "";
                    for (int i = 0; i < values.length; i++) {
                        valueStr = (i == values.length - 1) ? valueStr + values[i]
                                : valueStr + values[i] + ",";
                    }
                    //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
                    //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
                    params.put(name, valueStr);
                }
                boolean checkSignature = AlipaySignature.rsaCheckV1(params, AliPayUtils.alipayPublicKey, AlipayConstants.CHARSET_UTF8, AlipayConstants.SIGN_TYPE_RSA2);
//                String sign = params.get("sign");
//                System.out.println(sign);
//
//                String content = AlipaySignature.getSignCheckContentV1(params);
//                boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, AliPayUtils.alipayPublicKey, CHARSET);
                if (checkSignature) {
                    System.out.println("交易名称：" + params.get("subject"));
                    System.out.println("交易状态：" + params.get("trade_status"));
                    System.out.println("支付宝交易凭证：" + params.get("trade_no"));
                    System.out.println("商家订单号：" + params.get("out_trade_no"));
                    System.out.println("交易金额：" + params.get("total_amount"));
                    System.out.println("买家在支付宝的唯一id：" + params.get("buyer_id"));
                    System.out.println("买家付款时间：" + params.get("gmt_payment"));
                    System.out.println("买家付款金额：" + params.get("buyer_pay_amount"));
                    String trackingNumber = params.get("out_trade_no");
//            String payment =params.get("gmt_payment");
                    String alipayTradeNo = params.get("trade_no");
                    TestOrder order = new TestOrder();
                    order.setStatus("已支付");
                    order.setTradeNo(alipayTradeNo);
                    order.setOrderNo(params.get("out_trade_no"));
                    order.setTotalAmount(new BigDecimal(params.get("total_amount")));
                    log.info("支付成功=====订单信息==={}==", com.alibaba.fastjson.JSONObject.toJSONString(order));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }





    //=================================================手机支付======================

    /**
     * 手机支付测试
     * @return
     */
    @RequestMapping("/getAppOrder")
    public Object getOrderInfo(){
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, AliPayUtils.appId,
                AliPayUtils.appPrivateKey, FORMAT, CHARSET, AliPayUtils.alipayPublicKey, SIGN_TYPE);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("我是测试数据");
        model.setSubject("App支付测试Java");
        String orderNo=UUID.randomUUID().toString();
        model.setOutTradeNo(orderNo);
        model.setTimeoutExpress("30m");//调用请求过期时间
        model.setTotalAmount("1.5");
        model.setProductCode(AliPayUtils.PRODUCT_CODE2);
        request.setBizModel(model);
        request.setNotifyUrl(AliPayUtils.notifyUrl_app);
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            log.info("===支付宝手机支付订单数据={}====",response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理,然后前端调支付宝接口。
            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "完成";
    }


    @PostMapping("/notifyApp")
    public  String notify_url(HttpServletRequest request){
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, AliPayUtils.alipayPublicKey, CHARSET,SIGN_TYPE);
            if (!flag){
                return "fail";
            }

            log.info("===支付宝手机支付回调订单数据={}====", com.alibaba.fastjson.JSONObject.toJSONString(params));
            return "success";
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "fail";
        }
    }


}
